package cn.iocoder.mall.user.application.controller.seller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.common.utils.common.annotation.AutoLog;
import cn.iocoder.common.utils.common.api.vo.Result;
import cn.iocoder.common.utils.common.api.vo.SMSMQDTO;
import cn.iocoder.common.utils.common.system.query.QueryGenerator;
import cn.iocoder.common.utils.common.system.util.JwtUtil;
import cn.iocoder.common.utils.common.util.DateUtils;
import cn.iocoder.common.utils.common.util.ObjectUtils;
import cn.iocoder.common.utils.common.util.oConvertUtils;
import cn.iocoder.common.utils.modules.system.entity.VerificationCode;
import cn.iocoder.mall.shop.api.ShopClerkRelationShipService;
import cn.iocoder.mall.shop.api.ShopService;
import cn.iocoder.mall.shop.api.pojo.ShopClerkRelationShip;
import cn.iocoder.mall.shop.api.pojo.ShopDTO;
import cn.iocoder.mall.user.api.AppMessageService;
import cn.iocoder.mall.user.api.constant.AppMessageTypeEnum;
import cn.iocoder.mall.user.api.dto.AppMessageDTO;
import cn.iocoder.mall.user.api.entities.SellerVo;
import cn.iocoder.mall.user.application.vo.message.AppMessageVO;
import cn.iocoder.mall.user.application.vo.seller.SellerDTO;
import cn.iocoder.mall.user.biz.convert.UserConvert;
import cn.iocoder.mall.user.biz.dataobject.AppMessage;
import cn.iocoder.mall.user.biz.dataobject.Seller;
import cn.iocoder.mall.user.biz.service.IAppMessageService;
import cn.iocoder.mall.user.biz.service.IMemberService;
import cn.iocoder.mall.user.biz.service.ISellerService;
import cn.iocoder.mall.user.biz.untils.RedisUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.common.framework.constant.CommonConstant.SMS_ROCKET_VERIFY_CODE_TOPIC;

/**
 * @Description: 商户
 * @Author: jeecg-boot
 * @Date: 2019-10-23
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "商户")
@RestController
@RequestMapping("/seller")
public class SellerController {
    @Autowired
    private ISellerService sellerService;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RedisUtil redisUtil;
    @Reference(validation = "true", version = "${dubbo.consumer.ShopClerkRelationShipService.version}")
    ShopClerkRelationShipService relationShipService;

    @Autowired
    private IAppMessageService appMessageService;

    @Reference(validation = "true", version = "${dubbo.provider.AppMessageService.version}")
    private AppMessageService appService;

    @Reference(validation = "true", version = "${dubbo.consumer.ShopService.version}")
    private ShopService shopService;

    /**
     * 分页列表查询
     *
     * @param seller
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "商户-分页列表查询")
    @ApiOperation(value = "商户/店员-分页列表查询", notes = "商户/店员-分页列表查询")
    @GetMapping(value = "/web/list")
    public Result<IPage<Seller>> queryPageList(Seller seller,
                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                               HttpServletRequest req) {
        Result<IPage<Seller>> result = new Result<IPage<Seller>>();
        QueryWrapper<Seller> queryWrapper = QueryGenerator.initQueryWrapper(seller, req.getParameterMap());
        Page<Seller> page = new Page<Seller>(pageNo, pageSize);
        //增加判断条件，只查询未删除的
        queryWrapper.eq("is_delete",0);
        //只查询商户 0：商户，1：店员
        queryWrapper.eq("type",0);
        IPage<Seller> pageList = sellerService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param sellerVo
     * @return
     */
    @AutoLog(value = "商户-添加")
    @ApiOperation(value = "商户-添加", notes = "商户-添加")
    @PostMapping(value = "/merchant/add")
    public Result<?> add(@RequestBody SellerVo sellerVo) {

//        实体类转换
        Seller seller=new Seller();
        BeanUtil.copyProperties(sellerVo,seller);
        //查询该用户是否已添加过
        Seller seller1 = sellerService.getOneUser(sellerVo.getMobile());
            if(null!=seller1){
//            商户手机号已存在  修改is_delete为0   如果被删除  那么应该有管理员恢复主动申请不行
            return Result.error("商户已存在");
            } else {
                try {
                    seller.setType(0);
                    sellerService.save(seller);
                  return   Result.ok("添加成功！");
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                 return    Result.error("操作失败");
                }
            }
    }
    @PostMapping(value = "/web/add")
    public Result<?> addweb(@RequestBody SellerVo sellerVo) {

//        实体类转换
        Seller seller=new Seller();
        BeanUtil.copyProperties(sellerVo,seller);
        //查询该用户是否已添加过
        Seller seller1 = sellerService.getOneUser(sellerVo.getMobile());
        if(null!=seller1){
//            商户手机号已存在  修改is_delete为0   如果被删除  那么应该有管理员恢复主动申请不行
            return Result.error("商户已存在");
        } else {
            try {
                seller.setType(0);
                sellerService.save(seller);
                return   Result.ok("添加成功！");
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return    Result.error("操作失败");
            }
        }
    }

    /**
     * 编辑
     *
     * @param seller
     * @return
     */
    @AutoLog(value = "商户-编辑")
    @ApiOperation(value = "商户/店员-编辑", notes = "商户/店员-编辑")
    @PostMapping(value = "/merchant/edit")
    public Result<Seller> edit(@RequestBody Seller seller) {
        Result<Seller> result = new Result<Seller>();
        Seller sellerEntity = sellerService.getById(seller.getId());
        if (sellerEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = sellerService.updateById(seller);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }
    @PostMapping(value = "/web/edit")
    public Result<Seller> editWeb(@RequestBody Seller seller) {
        Result<Seller> result = new Result<Seller>();
        Seller sellerEntity = sellerService.getById(seller.getId());
        if (sellerEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = sellerService.updateById(seller);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }
    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商户-通过id删除")
    @ApiOperation(value = "商户/店员-通过id删除", notes = "商户/店员-通过id删除")
    @DeleteMapping(value = "/web/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        try {
            sellerService.deleteOneSeller(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "商户-批量删除")
    @ApiOperation(value = "商户/店员-批量删除", notes = "商户/店员-批量删除")
    @DeleteMapping(value = "/web/deleteBatch")
    public Result<Seller> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        Result<Seller> result = new Result<Seller>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.sellerService.deleteListSeller(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商户-通过id查询")
    @ApiOperation(value = "商户/店员-通过id查询", notes = "商户/店员-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<Seller> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<Seller> result = new Result<Seller>();
        Seller seller = sellerService.getById(id);
        if (seller == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(seller);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<Seller> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                Seller seller = JSON.parseObject(deString, Seller.class);
                queryWrapper = QueryGenerator.initQueryWrapper(seller, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<Seller> pageList = sellerService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "商户/店员列表");
        mv.addObject(NormalExcelConstants.CLASS, Seller.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商户/店员列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<Seller> listSellers = ExcelImportUtil.importExcel(file.getInputStream(), Seller.class, params);
                sellerService.saveBatch(listSellers);
                return Result.ok("文件导入成功！数据行数:" + listSellers.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    @GetMapping("/merchant/getPersonalInfo")
    public Result<?> getPersonalInfo() {

        Seller seller = sellerService.getById(JwtUtil.getUserInfoByToken().getUserId());
        if (seller == null || seller.getIsDelete() == 1 || seller.getState()
                == 1) {
            return Result.error("用户不存在");
        }
        SellerVo sellerVo = new SellerVo();
        BeanUtil.copyProperties(seller, sellerVo);

        return Result.ok(sellerVo);
    }

    @PostMapping("/merchant/updatePersonalInfo")
    public Result<?> updatePersonalInfo(@RequestBody SellerVo sellerVo){
        Seller seller=new Seller();
        BeanUtil.copyProperties(sellerVo,seller);
        seller.setId(JwtUtil.getUserInfoByToken().getUserId());
        try {
            sellerService.updateById(seller);
        }catch (Exception e){
            log.error(e.getMessage());
            return Result.error("修改失败");
        }

        return Result.ok();
    }

    @GetMapping("/merchant/getVerificationCode")
    public Result<?> getVerificationCode(@RequestParam String mobile){

        Seller seller=sellerService.getById(JwtUtil.getUserInfoByToken().getUserId());
        if (seller==null||seller.getState()==1||seller.getIsDelete()==1){
            return Result.error("账户状态异常");
        }

        String code= RandomUtil.randomNumbers(4);
        redisUtil.setSellerCode(mobile,code,4000);
        VerificationCode code1=new VerificationCode();
        code1.setCode(code);
        SMSMQDTO smsmqdto=new SMSMQDTO();
        smsmqdto.setMobile(mobile);
        smsmqdto.setCode(code);
        log.info("发送到mq");
        rocketMQTemplate.convertAndSend(SMS_ROCKET_VERIFY_CODE_TOPIC,smsmqdto);
        return Result.ok(code1);
    }

    @PostMapping("/merchant/updateMobile")
    public Result<?> updateMobile(@RequestBody SellerVo sellerVo){
        if (sellerVo.getMobile()==null||sellerVo.getCode()==null){
            return Result.error("");
        }
        //TODO 验证码逻辑
        String code1= (String) redisUtil.getSellerCode(sellerVo.getMobile());
        if (code1==null||!sellerVo.getCode().equals(code1)){
            return Result.error("");
        }
        Seller seller=new Seller();
        seller.setId(JwtUtil.getUserInfoByToken().getUserId());
        seller.setMobile(sellerVo.getMobile());
        sellerService.updateById(seller);

        AppMessageDTO app = new AppMessageDTO();
        app.setCreateTime(DateUtils.getDate());
        app.setTitle("更换手机号");
        app.setContent(sellerVo.getMobile());
        app.setType(AppMessageTypeEnum.CHANGE_PASSWORD_MOBILE.getValue());
        app.setReceiver(sellerVo.getMobile());
        appService.sendAppMessageToUser(app);

        return Result.ok();
    }

    /**
     * 获取该商户下的店员列表
     * @return
     */
    @GetMapping("/merchant/getListOfClerk")
    public Result<?> getListOfClerk(){
        Result result = new Result();
        String sellerId=JwtUtil.getUserInfoByToken().getUserId();
        try{
            List<SellerVo> list = sellerService.getListOfClerk(sellerId);
            CommonResult<List<ShopDTO>> commonResult=shopService.getShopLisByClerkIds(list.stream().map(SellerVo::getId).collect(Collectors.toList()));
            if (commonResult.isSuccess()){
                Map<String,List<ShopDTO>> map=commonResult.getData().stream().collect(Collectors.groupingBy(ShopDTO::getClerkId));
                Iterator<String> iterator=map.keySet().iterator();
                while (iterator.hasNext()){
                    String key=iterator.next();
                    for (SellerVo temp:list){
                        if (temp.getId().equals(key)){
                            temp.setShopList(UserConvert.INSTANCE.convert3(map.get(key)));
                            break;
                        }
                    }
                }
            }

            result.setResult(list);
            result.setCode(200);
            return result;
        }catch (Exception e){
            log.error("查询出错:"+e.getMessage());
            return Result.error(500,"查询出错");
        }
    }
    /**
     * 获取该商户下的店铺列表
     * @return
     */
    @GetMapping("/merchant/getListOfStores")
    public Result<?> getListOfStores(){
        Result result = new Result();
        String sellerId=JwtUtil.getUserInfoByToken().getUserId();
        try{
            List<ShopDTO> list = sellerService.getListOfStores(sellerId);
            if(list == null || list.isEmpty() || list.size() == 0){
                result.setMessage("该商户暂未店铺信息");
                return result;
            }
            result.setCode(200);
            result.setResult(list);
            return result;
        }catch (Exception e){
            log.error("查询出错"+e.getMessage());
            return Result.error(500,"查询出错");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/merchant/distributionShop")
    public Result<?> distributionShop(@RequestBody SellerVo sellerVo) throws Exception {
//        给店铺分配店员，，，，，分配之前，先把店员原先和店铺的关系删除
        if(!relationShipService.removeById(sellerVo.getClerkId()).isSuccess()){
            throw new Exception("删除失败");
        }
        ShopClerkRelationShip temp;

        if (sellerVo.getShopIds()==null){

        }
        else  {
            if (sellerVo.getShopIds().contains(",")){
                String[] strings=sellerVo.getShopIds().split(",");
                List<ShopClerkRelationShip> list=new ArrayList<>();
                for (String s:strings){
                    temp=new ShopClerkRelationShip();
                    temp.setClerkId(sellerVo.getClerkId());
                    temp.setShopId(s);
                    list.add(temp);
                }
               if (!relationShipService.saveBatch(list).isSuccess()){
                   throw new Exception("保存失败");
               }
            }
            else {
                temp=new ShopClerkRelationShip();
                temp.setShopId(sellerVo.getShopIds());
                temp.setClerkId(sellerVo.getClerkId());
                if (!relationShipService.save(temp).isSuccess()){
                    throw new Exception("保存失败");
                }

            }
        }

        return Result.ok();
    }


    @GetMapping("/merchant/getMessageList")
    public Result getMerchantMessageList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize){
        String userId=JwtUtil.getUserIdByToken();
        Page page=new Page<>();
        page.setSize(pageSize).setCurrent(pageNo);
        IPage<AppMessage> temp =appMessageService.getPageListOfMessage(page,userId);
        page.setTotal(temp.getTotal());
        page.setRecords(temp.getRecords().stream().map(o-> ObjectUtils.copyObject(o, AppMessageVO.class)).collect(Collectors.toList()));
        return Result.ok(page);

    }
    @GetMapping("/app/getNewMessageList")
    public Result getNewMessageList(@RequestParam Long id){
        List<AppMessage> appMessages=appMessageService.getNewMessageListById(JwtUtil.getUserIdByToken(),id);
        return Result.ok(ObjectUtils.copyList(appMessages,AppMessageVO.class));
    }
    @PostMapping("/merchant/updateMessageStatus")
    public Result updateMessageStatus(@RequestBody AppMessageVO vo){

        AppMessage appMessage=new AppMessage();
        appMessage.setIsRead(vo.getIsRead());
        appMessage.setId(vo.getId());

        appMessageService.updateById(appMessage);

        return Result.ok();
    }
}

